//
//  FlutterWxApiHandler.m
//  Pods-Runner
//
//  Created by lu on 8/11/2019.
//

#import "FlutterWxApiHandler.h"
#import "WXApi.h"
#import "WechatAuthSDK.h"
#import "WXApiObject.h"
#import "SendMessageToWXReq+requestWithTextOrMediaMessage.h"
#import "StringToWeChatScene.h"
#import "AppUtils.h"
#import "ThumbnailHelper.h"
#import "NSStringWrapper.h"
#import <Luban_iOS/UIImage+Luban_iOS_Extension_h.h>
#import <CoreImage/CoreImage.h>

@implementation FlutterWxApiHandler

NSObject <FlutterPluginRegistrar> *_wxRegistrar;

- (instancetype)initWithRegistrar:(NSObject <FlutterPluginRegistrar> *)registrar {
    self = [super init];
    if (self) {
        _wxRegistrar = registrar;
    }

    return self;
}

// MARK: - 微信注册、登录

// 注册微信
- (void)wxRegisterWithCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    NSString *wxAppId = call.arguments[@"appid"];
    NSString *universalLinks = call.arguments[@"iOSUniversalLinks"];
    Boolean isRegisterSuccess = [WXApi registerApp:wxAppId universalLink:universalLinks];
    if (isRegisterSuccess) {
        result(@YES);
    } else {
        result(@NO);
    }
}

// 是否安装微信
- (void)wxIsInstalledWithCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    Boolean isWxInstalled = WXApi.isWXAppInstalled;
    if (isWxInstalled) {
        result(@YES);
    } else {
        result(@NO);
    }
}

// 微信授权
- (void)wxAuthWithCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    NSString *scope = call.arguments[@"scope"];
    
    SendAuthReq *req = [[SendAuthReq alloc] init];
    req.scope = scope; // @"post_timeline,sns"
    req.state = @"wx_sdk_info_valley";
    
    [WXApi sendReq:req completion:^(BOOL success) {
        NSLog(@"微信授权=：%d", success);
        if (success) {
            result(@YES);
        } else {
            result(@NO);
        }
    }];
}

// MARK: - 微信分享

// 微信分享文本
- (void)wxShareTextWithCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    NSString *shareText = call.arguments[@"text"];
    NSString *shareScene = call.arguments[@"targetScene"];
    NSLog(@"分享到的平台shareScene: %@", shareScene);
    
    SendMessageToWXReq *req = [SendMessageToWXReq requestWithText:shareText
                                                   OrMediaMessage:nil
                                                            bText:YES
                                                            InScene:[StringToWeChatScene toScene:shareScene]];
    [WXApi sendReq:req completion:^(BOOL success) {
        if (success) {
            result(@YES);
        } else {
            result(@NO);
        }
    }];
}

// 微信分享图片
- (void)wxShareImageWithCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    NSString *imagePath = call.arguments[@"imageUrl"];
    FlutterStandardTypedData *imageData = call.arguments[@"imageData"];
    if (imageData != nil) {
        // 分享内存图片
        NSLog(@"00000");

        [self shareMemoryImage:call result:result imageData:imageData.data];
    }
//    else if ([imagePath hasPrefix:@"assets://"]) {
//        NSLog(@"11111");
//        [self shareAssetImage:call result:result imagePath:imagePath];
//    }
//    else if ([imagePath hasPrefix:SCHEMA_FILE]) {
//        [self shareLocalImage:call result:result imagePath:imagePath];
//    }
    else {
        NSLog(@"222222");
        // 默认分享网络图片
        [self shareNetworkImage:call result:result imagePath:imagePath];
    }
}

// 分享项目图片
- (void)shareAssetImage:(FlutterMethodCall *)call result:(FlutterResult)result imagePath:(NSString *)imagePath {
    NSLog(@"333333");
    NSString *thumbnail = call.arguments[@"thumbnail"];
    NSString *shareScene = call.arguments[@"targetScene"];

    NSLog(@"imagePath: %@", imagePath);
    
    if ([AppUtils isBlank:thumbnail]) {
        thumbnail = imagePath;
    }
    
    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
    dispatch_async(globalQueue, ^{
        
        NSLog(@"==== %@", [self readImageFromAssets:imagePath]);

        NSData *imageData = [NSData dataWithContentsOfFile:[self readImageFromAssets:imagePath]];

        UIImage *thumbnailImage = [self getThumbnail:thumbnail size:32765];

        dispatch_async(dispatch_get_main_queue(), ^{
            WXImageObject *ext = [WXImageObject object];
            ext.imageData = imageData;

            WXMediaMessage *message = [WXMediaMessage message];
            message.mediaObject = ext;
            [message setThumbImage:thumbnailImage];

            SendMessageToWXReq *req = [SendMessageToWXReq requestWithText:nil
                                                           OrMediaMessage:message
                                                                    bText:NO
                                                                  InScene:[StringToWeChatScene toScene:shareScene]];
            [WXApi sendReq:req completion:^(BOOL success) {
                if (success) {
                    result(@YES);
                } else {
                    result(@NO);
                }
            }];
        });
    });
}

// 分享内存图片
- (void)shareMemoryImage:(FlutterMethodCall *)call result:(FlutterResult)result imageData:(NSData *)imageData {
    NSString *thumbnail = call.arguments[@"thumbnail"];
    NSString *shareScene = call.arguments[@"targetScene"];
    
    UIImage *thumbnailImage = nil;
    if ([AppUtils isBlank:thumbnail]) {
        UIImage *tmp = [UIImage imageWithData:imageData];
        thumbnailImage = [ThumbnailHelper compressImage:tmp toByte:32765 isPNG:FALSE];
    } else {
        thumbnailImage = [ThumbnailHelper zipImageWithUrl:thumbnail];
//        thumbnailImage = [self getThumbnail:thumbnail size:32765];
    }
    
    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
    dispatch_async(globalQueue, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            WXImageObject *ext = [WXImageObject object];
            ext.imageData = imageData;

            WXMediaMessage *message = [WXMediaMessage message];
            message.mediaObject = ext;
            [message setThumbImage:thumbnailImage];
            
            SendMessageToWXReq *req = [SendMessageToWXReq requestWithText:nil
                                                           OrMediaMessage:message
                                                                    bText:NO
                                                                  InScene:[StringToWeChatScene toScene:shareScene]];
            [WXApi sendReq:req completion:^(BOOL success) {
                if (success) {
                    result(@YES);
                } else {
                    result(@NO);
                }
            }];
        });
    });
}

// 分享网络url图片
- (void)shareNetworkImage:(FlutterMethodCall *)call result:(FlutterResult)result imagePath:(NSString *)_imagePath {
    NSString *shareScene = call.arguments[@"targetScene"];
    NSString *thumbnail = call.arguments[@"thumbnail"];
    
    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
    dispatch_async(globalQueue, ^{
        NSURL *imageURL = [NSURL URLWithString:_imagePath];
        
        //下载图片
        NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
        UIImage *thumbnailImage = [self getThumbnail:thumbnail size:32765];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            WXImageObject *ext = [WXImageObject object];
            ext.imageData = imageData;
            
            WXMediaMessage *message = [WXMediaMessage message];
            message.mediaObject = ext;
            [message setThumbImage:thumbnailImage];
            
            SendMessageToWXReq *req = [SendMessageToWXReq requestWithText:nil
                                                           OrMediaMessage:message
                                                                    bText:NO
                                                                  InScene:[StringToWeChatScene toScene:shareScene]];
            [WXApi sendReq:req completion:^(BOOL success) {
                if (success) {
                    result(@YES);
                } else {
                    result(@NO);
                }
            }];
        });
    });
}

// 获取网络图片缩略图
- (UIImage *)getThumbnail:(NSString *)thumbnail size:(NSUInteger)size {
    UIImage *thumbnailImage = nil;

        if ([AppUtils isBlank:thumbnail]) {
            return nil;
        }
    
        NSLog(@"0-");

        if ([thumbnail hasPrefix:@"assets://"]) {
            NSData *imageData2 = [NSData dataWithContentsOfFile:[self readImageFromAssets:thumbnail]];
            UIImage *tmp = [UIImage imageWithData:imageData2];
            thumbnailImage = [ThumbnailHelper compressImage:tmp toByte:size isPNG:FALSE];
            NSLog(@"1-");
        } else {
            NSURL *thumbnailURL = [NSURL URLWithString:thumbnail];
            NSData *thumbnailData = [NSData dataWithContentsOfURL:thumbnailURL];
            UIImage *temp = [UIImage imageWithData:thumbnailData];
            UIImage *tmp = [self transferHeicToJpg:temp];
            thumbnailImage = [UIImage imageWithData:[UIImage lubanCompressImage:tmp]];
            
//            thumbnailImage = [self compressOriginalImage:tmp toWidth:50];
            //缩略图要小于32KB，否则无法调起微信,32KB = 32*1024B=32678
//            thumbnailImage = [ThumbnailHelper zipImageWithUrl:thumbnail];
//            thumbnailImage = [ThumbnailHelper compressImage:tmp toByte:size isPNG:FALSE];
            NSLog(@"3-");
        }
        
        NSLog(@"4-");

        return thumbnailImage;
}

- (UIImage *)transferHeicToJpg:(UIImage *)_image {
    CIImage *cimage = [[CIImage alloc] initWithImage:_image];
    CIContext *ciContext = [[CIContext alloc] init];
    if (@available(iOS 10.0, *)) {
        NSData *imageData = [ciContext JPEGRepresentationOfImage:cimage colorSpace:cimage.colorSpace options:@{}];
        NSLog(@"做了heic转换");
        return [UIImage imageWithData: imageData];
    } else {
        NSLog(@"没有做heic转换");
        return  _image;
    }
}

#pragma mark - 改变图片的大小
-(UIImage *)compressOriginalImage:(UIImage *)image toWidth:(CGFloat)targetWidth
{
    CGSize imageSize = image.size;
    CGFloat Originalwidth = imageSize.width;
    CGFloat Originalheight = imageSize.height;
    CGFloat targetHeight = Originalheight / Originalwidth * targetWidth;
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    [image drawInRect:CGRectMake(0,0,targetWidth,  targetHeight)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

// ------这种方法对图片既进行压缩，又进行裁剪
- (NSData *)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize;
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return UIImageJPEGRepresentation(newImage, 0.8);
}

// 从项目读取图片
- (NSString *)readImageFromAssets:(NSString *)imagePath {
    NSArray *array = [self formatAssets:imagePath];
    
    NSLog(@"array-: %@", array);
    
    NSString *key;
    if ([AppUtils isBlank:array[1]]) {
        key = [_wxRegistrar lookupKeyForAsset:array[0]];
    } else {
        key = [_wxRegistrar lookupKeyForAsset:array[0] fromPackage:array[1]];
    }
    
    NSLog(@"5-: %@", key);
    
    return [[NSBundle mainBundle] pathForResource:key ofType:nil];
}

- (NSArray *)formatAssets:(NSString *)originPath {
    NSString *path = nil;
    NSString *packageName = @"";
    NSInteger from = [@"assets://" length];
    NSInteger to = [originPath length];
    NSString *pathWithoutSchema = [originPath substringFromIndex:from toIndex:to];
    NSInteger indexOfPackage = [pathWithoutSchema lastIndexOfString:@"?package="];

    if (indexOfPackage != JavaNotFound) {
        path = [pathWithoutSchema substringFromIndex:0 toIndex:indexOfPackage];
        int begin = indexOfPackage + [@"?package=" length];
        packageName = [pathWithoutSchema substringFromIndex:begin toIndex:[pathWithoutSchema length]];
    } else {
        path = pathWithoutSchema;
    }

    return @[path, packageName];
}

// 微信分享音乐
- (void)wxShareMusicWithCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    NSString *musicUrl = call.arguments[@"musicUrl"];
    NSString *musicTitle = call.arguments[@"musicTitle"];
    NSString *musicDescription = call.arguments[@"musicDescription"];
    NSString *shareScene = call.arguments[@"targetScene"];
    
    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
    dispatch_async(globalQueue, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            WXMusicObject *ext = [WXMusicObject object];
            ext.musicUrl = musicUrl;
            
            WXMediaMessage *message = [WXMediaMessage message];
            message.title = musicTitle;
            message.description = musicDescription;
            message.mediaObject = ext;
            
            SendMessageToWXReq *req = [SendMessageToWXReq requestWithText:nil
                                                           OrMediaMessage:message
                                                                    bText:NO
                                                                  InScene:[StringToWeChatScene toScene:shareScene]];
            [WXApi sendReq:req completion:^(BOOL success) {
                if (success) {
                    result(@YES);
                } else {
                    result(@NO);
                }
            }];
        });
    });
}

// 微信分享视频
- (void)wxShareVideoWithCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    NSString *videoUrl = call.arguments[@"videoUrl"];
    NSString *videoTitle = call.arguments[@"videoTitle"];
    NSString *videoDescription = call.arguments[@"videoDescription"];
    NSString *shareScene = call.arguments[@"targetScene"];
    
    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
    dispatch_async(globalQueue, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            WXMediaMessage *message = [WXMediaMessage message];
            message.title = videoTitle;
            message.description = videoDescription;
            
            WXVideoObject *ext = [WXVideoObject object];
            ext.videoUrl = videoUrl;
            
            message.mediaObject = ext;

            SendMessageToWXReq *req = [SendMessageToWXReq requestWithText:nil
                                                           OrMediaMessage:message
                                                                    bText:NO
                                                                  InScene:[StringToWeChatScene toScene:shareScene]];
            [WXApi sendReq:req completion:^(BOOL success) {
                if (success) {
                    result(@YES);
                } else {
                    result(@NO);
                }
            }];
        });
    });
}

// 微信分享网页
- (void)wxShareWebPageWithCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    NSString *webPageUrl = call.arguments[@"webPageUrl"];
    NSString *webPageTitle = call.arguments[@"webPageTitle"];
    NSString *webPageDescription = call.arguments[@"webPageDescription"];
    NSString *thumbnail = call.arguments[@"thumbnail"];
    NSString *shareScene = call.arguments[@"targetScene"];
    FlutterStandardTypedData* imageTypeData = (FlutterStandardTypedData*)call.arguments[@"imageData"];
    NSLog(@"微信分享网页 -- 00");
    
    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
    dispatch_async(globalQueue, ^{
        
        NSLog(@"微信分享网页 -- 01");
        
        UIImage *thumbnailImage;
        if (thumbnail != (id) [NSNull null]) {
            NSLog(@"缩略图 thumbnail: %@", thumbnail);
            thumbnailImage = [self getThumbnail:thumbnail size:32765];
        } else if (imageTypeData != (id) [NSNull null]) {
            NSLog(@"微信分享网页 -- 02");
            // imageData
            thumbnailImage = [UIImage imageWithData: imageTypeData.data];
            NSLog(@"微信分享网页 -- 03");
        }
        
        NSLog(@"开始分享0");
        
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"开始分享1");
            WXWebpageObject *ext = [WXWebpageObject object];
            NSLog(@"开始分享1-");
            ext.webpageUrl = webPageUrl;
            
            NSLog(@"开始分享2");
            
            WXMediaMessage *message = [WXMediaMessage message];
            
            NSLog(@"开始分享3");
            message.title = webPageTitle;
            NSLog(@"开始分享4");
            message.description = webPageDescription;
            NSLog(@"开始分享5");
            message.mediaObject = ext;
            NSLog(@"开始分享6");
            [message setThumbImage:thumbnailImage];
            NSLog(@"开始分享7");
            
            SendMessageToWXReq *req = [SendMessageToWXReq requestWithText:nil
                                                           OrMediaMessage:message
                                                                    bText:NO
                                                                  InScene:[StringToWeChatScene toScene:shareScene]];
            NSLog(@"开始分享8");
            [WXApi sendReq:req completion:^(BOOL success) {
                if (success) {
                    NSLog(@"开始分享9");
                    result(@YES);
                } else {
                    NSLog(@"开始分享10");
                    result(@NO);
                }
            }];
        });
    });
}

// 微信分享小程序
- (void)wxShareMiniProgramWithCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    NSString *miniProgramWebPageUrl = call.arguments[@"miniProgramWebPageUrl"];
    NSString *miniProgramWebPageTitle = call.arguments[@"miniProgramWebPageTitle"];
    NSString *miniProgramWebPageDescription = call.arguments[@"miniProgramWebPageDescription"];
    NSString *miniProgramId = call.arguments[@"miniProgramId"];
    NSString *miniProgramPath = call.arguments[@"miniProgramPath"];
    // 小程序新版本的预览图二进制数据，大小不超过128K，自定义图片建议长宽比是 5:4
    NSData *miniProgramHdImageData = call.arguments[@"miniProgramHdImageData"];
    NSLog(@"0======");
    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
        dispatch_async(globalQueue, ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                WXMiniProgramType miniProgramType = WXMiniProgramTypeRelease;
                
                NSLog(@"1======");
                
                WXMiniProgramObject *ext = [WXMiniProgramObject object];
                ext.webpageUrl = miniProgramWebPageUrl;
                ext.userName = miniProgramId;
                ext.miniProgramType = miniProgramType;
                ext.path = miniProgramPath;
//                ext.hdImageData = miniProgramHdImageData;
                
                NSLog(@"2======");
                
                WXMediaMessage *message = [WXMediaMessage message];
                
                NSLog(@"3======");
                
                message.title = miniProgramWebPageTitle;
                message.description = miniProgramWebPageDescription;
                message.mediaObject = ext;
                
                NSLog(@"4======");

                SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
                req.bText = NO;
                req.message = message;
                req.scene = WXSceneSession;  //目前只支持会话
                [WXApi sendReq:req completion:^(BOOL success) {
                    NSLog(@"5======");
                    if (success) {
                        NSLog(@"微信分享小程序成功");
                        result(@YES);
                    } else {
                        NSLog(@"微信分享小程序失败");
                        result(@NO);
                    }
                }];
            });
        });
}

// 微信支付
- (void)wxPayWithCall:(FlutterMethodCall *)call result:(FlutterResult)result {

    NSLog(@"微信支付调用SDK");
    
    NSString *appId = call.arguments[@"appid"];
    NSLog(@"appId: %@", appId);
    
    NSString *payPartnerId = call.arguments[@"partnerid"];
    NSLog(@"payPartnerId: %@", payPartnerId);
    
    NSString *payPrepayId = call.arguments[@"prepayid"];
    NSLog(@"payPrepayId: %@", payPrepayId);
    
    NSString *payNonceStr = call.arguments[@"noncestr"];
    NSLog(@"payNonceStr: %@", payNonceStr);
    
    NSString *payPackageValue = call.arguments[@"package"];
    NSLog(@"payPackageValue: %@", payPackageValue);
    
    NSString *paySign = call.arguments[@"sign"];
    NSLog(@"paySign: %@", paySign);
    
    NSNumber *payTimestamp = call.arguments[@"timestamp"];
    UInt32 timeStamp = [payTimestamp unsignedIntValue];
    NSLog(@"timeStamp: %u", (unsigned int)timeStamp);
    
    PayReq *req = [[PayReq alloc] init];
    NSLog(@"111");
    req.openID = (appId == (id) [NSNull null]) ? nil : appId;
    NSLog(@"req.openID: %@", req.openID);
    req.partnerId = payPartnerId;
    NSLog(@"req.partnerId: %@", req.partnerId);
    req.prepayId = payPrepayId;
    NSLog(@"req.prepayId: %@", req.prepayId);
    req.nonceStr = payNonceStr;
    NSLog(@"req.nonceStr: %@", req.nonceStr);
    req.timeStamp = timeStamp;
    NSLog(@"req.timeStamp: %u", (unsigned int)req.timeStamp);
    req.package = payPackageValue;
    NSLog(@"req.package: %@", req.package);
    req.sign = paySign;
    NSLog(@"req.sign: %@", req.sign);
    
    [WXApi sendReq:req completion:^(BOOL success) {

        if (success) {
            NSLog(@"微信支付调用成功");
            result(@YES);
        } else {
            NSLog(@"微信支付调用失败");
            result(@NO);
        }
    }];
}

@end
